package org.xtense.model.actions;

import java.lang.reflect.Method;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodProxy;

import org.dom4j.Attribute;
import org.dom4j.Element;
import org.dom4j.tree.DefaultAttribute;
import org.xtense.engine.actions.UpdateAction;

public class AttributeInterceptor extends Interceptor {
	//	private static String setName = "setName";
	private static String setValue = "setValue";
	private static String setText = "setText";
	
	public AttributeInterceptor() {
		transaction = false;
		enhancer = new Enhancer();
		enhancer.setCallback(this);
	}
	
	public Attribute createAttribute(String name, String value) {
		enhancer.setSuperclass(DefaultAttribute.class);
		Object o = enhancer.create(new Class[] { String.class, String.class },
				new Object[] { name, value });
		return (Attribute) o;
	}

	@Override
	public Object intercept(Object o, Method method, Object[] args,
			MethodProxy proxy) throws Throwable {
		if (transaction) {
			

			// if (setName.equals(method.getName())) {
			// Element base = ((Attribute) o).getParent();
			// int docId = getDocIDFromNode(base);
			// int elePre = getElementPreFromNode(docId, base);
			// UpdateAction.getInstance(docId).getCache().cacheSql(
			// UpdateHelper.getInstance().changeAttributeName(docId,
			// elePre, args[0].toString()));
			// } else
			if (setValue.equals(method.getName())
					|| setText.equals(method.getName())) {
				Element base = ((Attribute) o).getParent();
				int docId = getDocIDFromNode(base);
				int elePre = getElementPreFromNode(docId, base);
				UpdateAction.getInstance(docId).getCache().cacheSql(
						UpdateHelper.getInstance().changeAttributeValue(docId,
								elePre, args[0].toString()));
			}			
		}
		return proxy.invokeSuper(o, args);
	}

}
